/*
 * tileMap.java
 *
 * Copyright (C) 2008 Paul Nettleship
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 * 
 */
package staticTrailExplorer;

import java.awt.Color;
import java.awt.Graphics;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 *
 * @author codebauer
 */
public class tileMap
   {
   public static location calibratedMarks[] = {null,null};
   public location screenRef;
   public location uncalibratedMarks[] = {null,null};
   public int tileWidth,tileHeight;
   public  boolean calibrated;
   public String name;
   private tileCache myCache;
   private mapDataIF mapData;
   private int minZoom, maxZoom;
   private BufferedImage missingTile;

   public tileMap(mapDataIF mapData, tileCache myCache, File phile)
      {
      this.mapData = mapData;
      this.myCache = myCache;
      tileWidth = 256;
      tileHeight = 256;
      screenRef = mapData.getDefaultStartLocation();

      /* Draw empty tile! */
      missingTile = new BufferedImage(tileWidth,tileHeight,BufferedImage.TYPE_INT_RGB);
      Graphics g = missingTile.createGraphics();
      g.setColor(Color.darkGray);
      g.fillRect(0, 0, tileWidth, tileHeight);
      //g.setColor(Color.RED);
      //g.drawLine(0        , 0         ,0       ,tileHeight);
      //g.drawLine(0        ,tileHeight,tileWidth,tileHeight);
      //g.drawLine(tileWidth,tileHeight,tileWidth,0         );
      //g.drawLine(tileWidth,0         ,0        ,0         );
      //g.drawLine(0        ,0         ,tileWidth,tileHeight);
      //g.drawLine(0        ,tileHeight,tileWidth,0          );
      
      mapData.init(this);
      if (phile != null)
         {
         name = phile.getName();
         try
            {
            if (phile.exists())
               {
               /* Open atlas file */
               mapData.openInput(phile);
               }
            else
               {
               /* Create atlas file */
               mapData.openOutput(phile);
               }
            }
         catch (IOException ex)
            {
            System.out.print(ex);
            }
         }
      else
         {
         name = "";
         }
      }

   
   public void display(Graphics g)
      {
      Rectangle paintArea = g.getClipBounds();
      for (double displayY = paintArea.getMinY();
         displayY - tileHeight < paintArea.getMaxY();
         displayY += tileHeight)
         {
         for (double displayX = paintArea.getMinX();
            displayX - tileWidth < paintArea.getMaxX();
            displayX += tileWidth)
            {
            location loc = new location(getScreenRef());
            loc.move((int) displayX, (int) displayY);
            BufferedImage tile = getCachedMapTile(loc, this, false);
            g.drawImage(tile, loc.getTileOrigX(this), loc.getTileOrigY(this), null);
            }
         }
      drawMarkers(g);
      }
   
   public void drawMarkers(Graphics g)
      {
      Rectangle paintArea = g.getClipBounds();
      location[] markers = calibratedMarks;
      if (calibrated == false )
         markers = uncalibratedMarks;

      for (int i = 0; i < markers.length; i++)
         {
         if (markers[i] != null)
            {
            g.drawLine(markers[i].getDisplayX(this), (int) paintArea.getMinY(),
               markers[i].getDisplayX(this), (int) paintArea.getMaxY());
            g.drawLine((int) paintArea.getMinX(), markers[i].getDisplayY(this),
               (int) paintArea.getMaxX(), markers[i].getDisplayY(this));
            }
         }
      }
   
   public void setMarker(int i, int x, int y)
      {
      location[] markers = calibratedMarks;
      if( calibrated == false )
         markers = uncalibratedMarks;

      if( markers[i] == null )
         markers[i]  = new location(0,0,0);
      markers[i].set(getScreenRef().getPixelX(this) + x, getScreenRef().getPixelY(this) + y, getScreenRef().getZoom() );
      }
   
   public void moveRef(int x, int y)
      {
      screenRef.move(x, y);
      }
   
   public void doZoom(int x,int y, int z)
      {
      getScreenRef().move(x, y);
      getScreenRef().setZoom( z + getScreenRef().getZoom() );
      getScreenRef().move(-x, -y);
      }
   
   public location getScreenRef()
      {
      return screenRef;
      }
   
   public mapDataIF getMapData()
      {
      return mapData;
      }

   public void saveMap( tileMap outputMap ) throws IOException
      {
      for (int z = minZoom; z <= maxZoom; z++)
         {
         /* Set map zoom */
         doZoom(0, 0, z - getScreenRef().getZoom());

         /* Top left mark */
         int minX = calibratedMarks[0].getPixelX(this);
         int minY = calibratedMarks[0].getPixelY(this);
         if (calibratedMarks[1].getPixelX(this) < minX)
            minX = calibratedMarks[1].getPixelX(this);
         if (calibratedMarks[1].getPixelY(this) < minY)
            minY = calibratedMarks[1].getPixelY(this);

         /* Bottom right mark */
         int maxX = calibratedMarks[0].getPixelX(this);
         int maxY = calibratedMarks[0].getPixelY(this);
         if (calibratedMarks[1].getPixelX(this) > maxX)
            maxX = calibratedMarks[1].getPixelX(this);
         if (calibratedMarks[1].getPixelY(this) > maxY)
            maxY = calibratedMarks[1].getPixelY(this);

         for (int y = minY; y - tileHeight < maxY; y += tileHeight)
            {
            for (int x = minX; x - tileWidth < maxX; x += tileWidth)
               {
               location loc = new location(x, y, z);
               BufferedImage tile = getCachedMapTile(loc, this, true );
               System.out.print("saving;" + loc.getName(outputMap) + "\n");
               outputMap.getMapData().saveMapTile(tile, loc);
               }
            }
         }
      outputMap.getMapData().close();
      }

   public boolean setZoomRange(int z1, int z2)
      {
      int minZ = z1;
      int maxZ = z2;

      if (z1 > z2)
         {
         minZ = z2;
         maxZ = z1;
         }

      /* Sanity check on zoom range */
      if ((minZ < location.minZoom) || (maxZ > location.maxZoom))
         {
         return false;
         }

      this.minZoom = minZ;
      this.maxZoom = maxZ;
      return true;
      }

   private BufferedImage getCachedMapTile(location loc,tileMap map, boolean blocking)
      {
      BufferedImage tile;
      if( myCache != null )
         tile = myCache.get(map, loc, blocking);
      else 
         tile = mapData.loadMapTile(loc);
      if( tile == null )
         tile = missingTile;
      return tile;
      }
}
